var gulp = require("gulp"),
	fs = require("fs"),
	path = require("path"),
	cssmin = require("gulp-uglifycss"),
	sass = require("gulp-sass"),
	imgmin = require('gulp-imagemin'),
	jsmin = require("gulp-uglify"),
	rename = require("gulp-rename"),
	changedInPlace = require('gulp-changed-in-place'),//不管修改哪个文件，gulp会简化DEST里的html文件
	preprocess = require('gulp-preprocess'),
	del = require("del"),
	merge = require('merge-stream'),
	minifyHTML = require('gulp-htmlmin'), //简化html
	concat = require('gulp-concat'),
	cache = require('gulp-cache'),
	// notify = require("gulp-notify"),
	browserSync = require('browser-sync').create(),

	// getGulpPath = require("./gulp/index"),
	dist = "dist/",
	srcWeb = "src/",
	gulpPath = "./gulp/";
var reload = browserSync.reload;
//读取文件列表
var configPathsFileList = fs.readdirSync(gulpPath);
//生成所有的配置文件对象
var configPaths = getPaths();
// js压缩
gulp.task("jsmin", ["cleanStatic"], function (e) {
	var task = [],
		jsPath = configPaths.index.jsPath
	if (process.env.NODE_ENV == 'production') {
		for (var key in jsPath) {
			var pipeJs = null
			pipeJs = gulp.src(jsPath[key])
				.pipe(concat(key))
				// .pipe(jsmin())
				.pipe(gulp.dest(dist + "js"));
		}
	} else {
		for (var key in jsPath) {
			var pipeJs = null
			pipeJs = gulp.src(jsPath[key])
				.pipe(concat(key))
				.pipe(jsmin())
				.on("error",function(err){
					console.log('Less Error!', err.message);
					this.emit('end');
				})
				.pipe(gulp.dest(dist + "js"));
		}
	}
	task.push(pipeJs)
	return merge(task)
});
// css压缩
gulp.task("cssmin", ["cleanStatic"], function () {
	var cssPath = configPaths.index.cssPath
	var _taskjs = []
	if (process.env.NODE_ENV == 'production') {
		for (var key in cssPath) {
			var pipeCss = null
			pipeCss = gulp.src(cssPath[key])
				.pipe(concat(key))
				.pipe(gulp.dest(dist + "css"));
			_taskjs.push(pipeCss)
		}
	} else {
		for (var key in cssPath) {
			var pipeCss = null
			pipeCss = gulp.src(cssPath[key])
				.pipe(concat(key))
				.pipe(cssmin())
				.pipe(gulp.dest(dist + "css"));
			_taskjs.push(pipeCss)
		}
	}
	return merge(_taskjs)
});
gulp.task('sass', ['cleanStatic'], function () {
	var cssPath = configPaths.index.cssPath
	var _taskjs = []
	console.log('---', process.env.NODE_ENV)
	new Promise(function (resolve, reject) {
		if (process.env.NODE_ENV == 'production') {
			for (var key in cssPath) {
				var pipeCss = null
				pipeCss = gulp.src(cssPath[key])
					.pipe(sass())
					.on('error', function (e) {
						return reject(e) && this.end();
					})
					.pipe(concat(key))
					.pipe(gulp.dest(dist + "css"))
					.on('end', resolve)
					.pipe(reload({ stream: true }));
				_taskjs.push(pipeCss)
			}
		} else {
			for (var key in cssPath) {
				var pipeCss = null
				pipeCss = gulp.src(cssPath[key])
					.pipe(sass())
					.on('error', function (e) {
						return reject(e) && this.end();
					})
					.pipe(concat(key))
					.pipe(cssmin())
					.pipe(gulp.dest(dist + "css"))
					.on('end', resolve)
					.pipe(reload({ stream: true }));;
				_taskjs.push(pipeCss)
			}
		}
	});
	return merge(_taskjs)
});
// 压缩图片
gulp.task("images", ["cleanStatic"], function () {
	gulp.src(srcWeb + 'images/**/**/**/*.*')
		.pipe(cache(imgmin({
			optimizationLevel: 5,
			progressive: true,
			interlaced: true
		})))
		.pipe(gulp.dest(dist + 'images'))
});
gulp.task('copy', ["cleanStatic"], function () {
	return gulp.src(srcWeb + 'js/plugins/**/**/**/**/**/*')
		.pipe(gulp.dest(dist + 'js/plugIns'))
})
gulp.task('htmlmin', ["cleanHtml"], function () {
	gulp.src(srcWeb + 'views/**/*.html')
		.pipe(changedInPlace({ firstPass: true }))
		// .pipe(minifyHTML({ collapseWhitespace: true }))
		.pipe(gulp.dest(dist + 'views'))
		.pipe(browserSync.stream());
});
// 启动本地服务
gulp.task("auto", function (cb) {
	browserSync.init({
		server: {
			baseDir: './'
		}

	});
	// browserSync.init({
	//     proxy: "http://www.hfnetdata.com"
	// });
	gulp.watch(srcWeb + "/**/*", ["copy", "jsmin", "sass", 'images','htmlmin'], reload);
	cb();
});
gulp.task("uat", function (cb) {
	// browserSync.init({
	// 	server: {
	// 		baseDir: './'
	// 	}

	// });
	browserSync.init({
	    proxy: "http://www.hfnetdata.com"
	});
	// gulp.watch(srcWeb + "/**/*", ["copy", "jsmin", "sass", 'images',''], reload);
	cb();
});
gulp.task("cleanStatic", function (cb) {
	return del([dist + 'css', dist + 'images', dist + 'js']);
});
gulp.task("cleanHtml", function (cb) {
	return del([dist + 'views/html']);
});

gulp.task("default", ["auto"]);
/**
 * [getPaths 生成所有的配置文件]
 * @return {[type]} [description]
 */
function getPaths() {
	var _configPaths = {};
	//循环文件列表处理
	configPathsFileList.map((_path) => {
		if (_path === "index.js" || _path === ".svn") {
			return;
		}
		try {
			var key = _path.replace("Entry.js", "");
			_configPaths[key] = require(gulpPath + _path);
		} catch (e) {
			console.error(_path + "is error!", e);
		}
	});
	return _configPaths;
}
